package org.boot.easyapi.core.dao;

import lombok.extern.slf4j.Slf4j;
import org.boot.easyapi.core.entity.ApiResponseDO;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Repository("easyapi-apiRespRepository")
public class ApiRespRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public List<ApiResponseDO> getListByKey(String tableName, String key) {
        String sql = "SELECT * FROM easyapi_core_response WHERE resp_key = ? AND table_name = ? ";
        List<Object> params = Arrays.asList(key, tableName);
        return jdbcTemplate.queryForList(sql, ApiResponseDO.class, params);
    }

    public String getFieldsByKey(String tableName, String key) {
        String sql = "SELECT fields FROM easyapi_core_response WHERE resp_key = ? AND table_name = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, (rs, rowNum) -> rs.getString("fields"), new Object[]{key, tableName});
        } catch (EmptyResultDataAccessException e) {
            log.error("未找到RespKey:" + key + "的配置");
            return null;
        }
    }

}
